﻿using System;
using System.Data;
using System.Runtime.Serialization;

namespace OpenComposite.HumanActivity.Contracts
{
	[DataContract(Name = "Attachment", Namespace = "http://www.theopencomposite.com/humanactivities")]
	public class AttachmentItem : ItemBase
	{
		#region Initialization
		/// <summary>
		/// Initializes a new instance of the <see cref="AttachmentItem"/> class.
		/// </summary>
		/// <param name="workflowInstanceId">The workflow instance id.</param>
		/// <param name="activityId">The activity id.</param>
		/// <param name="userId">The user id.</param>
		public AttachmentItem(Guid workflowInstanceId, int? activityId, int userId)
		{
			this.WorkflowInstanceId = workflowInstanceId;
			this.ActivityId = activityId;
			this.CreatedById = userId;
			this.CreatedDateTime = DateTime.Now;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="AttachmentItem"/> class.
		/// </summary>
		/// <param name="rowAttachment">An attachments table datarow.</param>
		public AttachmentItem(DataRow rowAttachment)
		{
			try {
				this.AttachmentId = (int)rowAttachment["attachment_id"];
				if ( rowAttachment.Table.Columns.Contains("workflow_instance_id") ) {
					this.WorkflowInstanceId = (Guid)rowAttachment["workflow_instance_id"];
				}
				this.ActivityId = getNullableInt(rowAttachment, "activity_id");

				this.Name = rowAttachment["attachment_nm"] as string;
				this.Description = rowAttachment["attachment_desc"] as string;
				this.FileName = rowAttachment["attachment_filenm"] as string;

				this.CreatedById = (int)rowAttachment["created_by"];
				this.CreatedDateTime = getNullableDateTime(rowAttachment, "created_dt");

				this.LastModifiedById = getNullableInt(rowAttachment, "lastmodified_by");
				this.LastModifiedDateTime = getNullableDateTime(rowAttachment, "lastmodified_dt");
			} catch ( Exception ex ) {
				throw new InvalidOperationException("Invalid notes datarow.", ex);
			}
		}
		#endregion

		#region Data Members
		[DataMember]
		public int? AttachmentId { get; private set; }
		[DataMember]
		public Guid WorkflowInstanceId { get; private set; }
		[DataMember]
		public int? ActivityId { get; private set; }

		[DataMember]
		public string Name { get; set; }
		[DataMember]
		public string Description { get; set; }
		[DataMember]
		public string FileName { get; set; }

		[DataMember]
		public byte[] Data { get; set; }

		[DataMember]
		public int CreatedById { get; private set; }
		[DataMember]
		public DateTime? CreatedDateTime { get; private set; }
		[DataMember]
		public int? LastModifiedById { get; set; }
		[DataMember]
		public DateTime? LastModifiedDateTime { get; private set; }
		#endregion
	}
}
